const consul = require('consul')();

const serviceMethod = consul.health.service;
const serviceListMethod = consul.catalog.service.list;
let watchList = [];

class Watch {
    /**
     * 添加对指定服务健康状态的监听，只监听状态为passing的服务
     * @param  {} config
     */
    service(config) {
        const {service, success, error} = config;
        if(service) {
            const serviceWatch = consul.watch({
                method: serviceMethod,
                options: { service: service, passing: true }
            });
            serviceWatch.on('change', (data, res) => {
                if(success) success(data, res);
            });
    
            serviceWatch.on('error', err => {
                if(error) error(err);
            });
    
            watchList.push(serviceWatch);
        }
    }

    list(config) {
        const serviceListWatch = consul.watch({ method: serviceListMethod });
        const {success, error} = config;
        serviceListWatch.on('change', (data, res) => {
            if(success) config.success(data, res);
        });

        serviceListWatch.on('error', err => {
            if(error) error(err);
        });

        watchList.push(serviceListWatch);
    }

    stop() {
        watchList.forEach(watchItem => {
            watchItem.end();
        });
        watchList = [];
    }
}

module.exports = new Watch();

